<?php
namespace app\common\model;
use think\Request;

/**
 * 微信群发消息模型
 */
class WechatBatchSend extends BaseModel
{
    protected $name = 'wechat_batch_send';
	
	/**
     * 消息类型
     */
    public function getMsgTypeAttr($value)
    {
        $status = [
			'mpnews' => '图文', 
			'text' => '文本', 
			'image' => '图片', 
			'video' => '视频', 
			'voice' => '语音', 
			'music' => '音乐', 
			'wxcard' => '卡券'
		];
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 群发状态
     */
    public function getStatusAttr($value)
    {
        $status = [
			0 => '未知错误',
			10 => '待群发', 
			20 => '群发中', 
			30 => '群发成功', 
			40 => '群发失败', 
			10001 => '涉嫌广告', 
			20001 => '涉嫌政治', 
			20004 => '涉嫌社会',
			20002 => '涉嫌色情',
			20006 => '涉嫌违法犯罪',
			20008 => '涉嫌欺诈',
			20013 => '涉嫌版权',
			22000 => '涉嫌互推',
			21000 => '涉嫌其他',
			30001 => '原创不能群发',
			30002 => '原创不能群发',
			30003 => '原创不能群发',
			40001 => '管理员拒绝',
			40002 => '管理员超时'
		];
        return ['text' => $status[$value], 'value' => $value];
    }
	
    /**
     * 获取列表
     */
    public function getList()
    {
        $wxapp_id = self::$wxapp_id;
        $filter = [];
        $wxapp_id < 1 && $filter['wxapp_id'] = 0;
        // 执行查询
        return $this->where($filter)
			->order('wechat_batch_send_id','desc')
            ->paginate(15, false, [
                'query' => Request::instance()->request()
            ]);
    }
    /**
     * 获取详情
     */
    public static function detail($wechat_batch_send_id)
    {
        return self::get($wechat_batch_send_id);
    }
	
	/**
     * 获取详情 - 回调
     */
    public static function getMsg($msg_id)
    {
		$where = ['msg_id' => $msg_id];
        return self::where($where)->find();
    }

    /**
     * 添加
     */
    public function add(array $data)
    {
        $data['wxapp_id'] = self::$wxapp_id;
        if($data['wxapp_id'] < 1){
            $data['wxapp_id'] = 0;
            $result= $this->preview_msg($data);
            if($result['errcode'] != 0){
                $this->error = wx_err_msg($result['errcode']);
                return false;
            }
        }
        return $this->allowField(true)->save($data);
    }

    /**
     * 编辑
     */
    public function edit($data)
    {
        $data['wxapp_id'] = self::$wxapp_id;
        if($data['wxapp_id'] < 1){
            $data['wxapp_id'] = 0;
            $result= $this->preview_msg($data);
            if($result['errcode'] != 0){
                $this->error = wx_err_msg($result['errcode']);
                return false;
            }
        }
        return $this->allowField(true)->save($data) !== false;
    }

    /**
     * 删除
     */
    public function remove()
    {
        $access_token = getAccessToken($this['wxapp_id'],0);
        $url = ' https://api.weixin.qq.com/cgi-bin/message/mass/delete?access_token='.$access_token;
        $post = ['msg_id' => $this['msg_id']];
        $result = json_decode(http_post($url,$post),true);
        if($result['errcode'] != 0){
            $this->error = wx_err_msg($result['errcode']);
            return false;
        }
        return $this->delete();
    }
    
    /**
     * 根据OpenID列表群发
     */
    public function send()
    {
        if(!empty($this->msg_id)){
            $this->error = '群发任务已存在';
            return false;
        }
        $open_id = StoreUser::where(['wechat_open_id' => ['<>','']])->column('wechat_open_id');
        //图文消息
        if($this['msg_type']['value']=='mpnews'){
            $post = [
                'touser' => $open_id,
                'mpnews' => [
                    'media_id' => $this['content']
                ],
                'msgtype' => 'mpnews',
                'send_ignore_reprint' => $this['send_ignore_reprint']
            ];
        }
        //文本消息
        if($this['msg_type']['value']=='text'){
            $post = [
                'touser' => $open_id,
                'msgtype' => 'text',
                'text' => [
                    'content' => $this['content']
                ]
            ];
        }
        //语音消息
        if($this['msg_type']['value']=='voice'){
            $post = [
                'touser' => $open_id,
                'voice' => [
                    'media_id' => $this['content']
                ],
                'msgtype' => 'voice'
            ];
        }
        //图片消息
        if($this['msg_type']['value']=='image'){
            $post = [
                'touser' => $open_id,
                'images' => [
                    'media_ids' => [
                        0 => $this['content']
                    ],
                    'recommend' => $this['recommend'],
                    'need_open_comment' => $this['need_open_comment'],
                    'only_fans_can_comment' => $this['only_fans_can_comment']
                ],
                'msgtype' => 'image'
            ];
        }
        //视频消息
        if($this['msg_type']['value']=='video'){
            $post = [
                'touser' => $open_id,
                'mpvideo' => [
                    'media_id' => $this['content'],
                    'title' => $this['title'],
                    'description' => $this['description']
                ],
                'msgtype' => 'mpvideo'
            ];
        }
        //卡券消息
        if($this['msg_type']['value']=='wxcard'){
            $post = [
                'touser' => $open_id,
                'wxcard' => [
                    'card_id' => $this['content']
                ],
                'msgtype' => 'wxcard'
            ];
        }
        $access_token = getAccessToken('',0);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token='.$access_token;
        $result = json_decode(http_post($url,$post),true);
        if($result['errcode'] != 0){
            $this->error = wx_err_msg($result['errcode']);
            return false;
        }
        $this->msg_id = $result['msg_id'];
        $this->fans_count = sizeof($open_id);
        $this->status = 20;
        return $this->save() !== false;
    }
    
    /**
     * 发布预览消息
     */
    private function preview_msg($data)
    {
        $values = WebSet::getItem('web');
        $open_id = $values['open_id'];
        //图文消息
        if($data['msg_type']=='mpnews'){
            $post = [
                'touser' => $open_id,
                'mpnews' => ['media_id' => $data['content']],
                'msgtype' => 'mpnews'
            ];
        }
        //文本消息
        if($data['msg_type']=='text'){
            $post = [
                'touser' => $open_id,
                'text' => ['content' => $data['content']],
                'msgtype' => 'text'
            ];
        }
        //语音消息
        if($data['msg_type']=='voice'){
            $post = [
                'touser' => $open_id,
                'voice' => ['media_id' => $data['content']],
                'msgtype' => 'voice'
            ];
        }
        //图片消息
        if($data['msg_type']=='image'){
            $post = [
                'touser' => $open_id,
                'image' => ['media_id' => $data['content']],
                'msgtype' => 'image'
            ];
        }
        //视频消息
        if($data['msg_type']=='video'){
            $post = [
                'touser' => $open_id,
                'mpvideo' => ['media_id' => $data['content']],
                'msgtype' => 'mpvideo'
            ];
        }
        //卡券消息
        if($data['msg_type']=='wxcard'){
            $post = '{
                "touser":"'.$open_id.'",
                "wxcard":{
                    "card_id":"'.$data['content'].'",
                    "card_ext": "{
                        "code":"",
                        "openid":"",
                        "timestamp":"",
                        "signature":""
                    }
                    "msgtype":"wxcard"
                }';
            $post = [
                'touser' => $open_id,
                'wxcard' => [
                    'card_id' => $data['content'],
                    'card_ext' => [
                        'code' => '',
                        'openid' => '',
                        'timestamp' => '',
                        'signature' => ''
                    ]
                ],
                'msgtype' => 'wxcard'
            ];
        }
        $access_token = getAccessToken($data['wxapp_id'],0);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token='.$access_token;
        return json_decode(http_post($url,$post),true);
    }

}
